package com.example.fw;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;


public class ApplicationManager {

	private WebDriver driver;
	public String hostUrl;
	public String mainUrl;	
	
	private NavigationHelper navigationHelper;
	private GroupHelper groupHelper;
	private ContactHelper contactHelper;
	private Properties properties;
	private HibernateHelper hibernateHelper;
	private ApplicationModelGroups modelGroups;
	private ApplicationModelContacts modelContacts;
	
	public ApplicationManager(Properties properties) {
		this.properties = properties;
		modelGroups = new ApplicationModelGroups();
		modelGroups.setGroups(getHibernateHelper().listGroups());
		modelContacts = new ApplicationModelContacts();
		modelContacts.setContacts(getHibernateHelper().listContacts());
	}
	
	public void stop() {
		driver.quit();
	}
	
	public ApplicationModelGroups getModelGroups() {
		return modelGroups;
	}
	
	public ApplicationModelContacts getModelContacts() {
		return modelContacts;
	}
	
	public NavigationHelper navigateTo() {
		if (navigationHelper == null) {
			navigationHelper = new NavigationHelper(this);
		}
		return navigationHelper;
	}

	public GroupHelper getGroupHelper() {
		if (groupHelper == null) {
			groupHelper = new GroupHelper(this);
		}
		return groupHelper;
	}
	
	public ContactHelper getContactHelper() {
		if (contactHelper == null) {
			contactHelper = new ContactHelper(this);
		}
		return contactHelper;
	}

	public HibernateHelper getHibernateHelper() {
		if (hibernateHelper == null) {
			hibernateHelper = new HibernateHelper(this);
		}
		return hibernateHelper;
	}

	public WebDriver getDriver() {
		String browser = properties.getProperty("browser");
		if (driver == null) {
			if ("firefox".equals(browser)){
				driver = new FirefoxDriver();
			} else if ("ie".equals(browser)) {
				driver = new InternetExplorerDriver();
			} else {
				throw new Error("Unsupported browser:" + browser);
			}
		    hostUrl = properties.getProperty("hostUrl");
		    mainUrl = "addressbookv4.1.4/";
		    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
				driver.get(hostUrl + mainUrl);
		}
		return driver;
  }

	public String getHostUrl() {
		return hostUrl;
	}

	public String getMainUrl() {
		return mainUrl;
	}
	
	public String getProperty(String key) {
		return properties.getProperty(key);
	}

}
